﻿using System;

namespace McmWinFormsApplication1
{
    public static class Env
    {
        private static McmComponentContainer _components;

        /// <summary>
        ///     Component container broadcasts messages and is a sort of service container
        /// </summary>
        public static McmComponentContainer Components
        {
            get
            {
                if (_components == null)
                {
                    throw new InvalidOperationException("Please execute the Initialize() method first.");
                }
                return _components;
            }
        }

        /// <summary>
        ///     Post a message to the main message channel
        /// </summary>
        /// <param name="message"></param>
        public static void PostMessage(object message)
        {
            if (message == null) throw new ArgumentNullException("message");
            Components.Messages.Post(message);
        }

        /// <summary>
        ///     Must be invoked in the UI thread.
        ///     Otherwise the SynchronizationContext of the UI-Thread will not be created
        ///     and no UI synchronization can be made.
        /// </summary>
        public static void Initialize()
        {
            if (_components != null)
            {
                throw new InvalidOperationException("Env.Initialize() may not be invoked more than once.");
            }

            // Instantiating Components
            _components = new McmComponentContainer();
            _components.Initialize();
        }

        /// <summary>
        ///     Must be invoked before the program end.
        ///     Otherwise message channels block the program and the application cannot be closed.
        /// </summary>
        public static void ShutDown()
        {
            if (_components != null)
            {
                _components.Dispose();
                _components = null;
            }
        }
    }
}